<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <!-- 导入页面的基本样式 -->
    <link rel="stylesheet" href="./css/search.css" />
    <!-- 导入 jQuery -->
    <script src="./lib/jquery.js"></script>
    <script src="./lib/template-web.js"></script>
    <script id="list-tpl" type="text/html">
        {{each result}}
        <div id="suggest-item">{{$value[0]}}</div>
        {{/each}}
    </script>
</head>

<body>
    <div class="container">
        <!-- Logo -->
        <img src="./images/taobao_logo.png" alt="" class="logo" />

        <div class="box">
            <!-- tab 栏 -->
            <div class="tabs">
                <div class="tab-active">宝贝</div>
                <div>店铺</div>
            </div>
            <!-- 搜索区域（搜索框和搜索按钮） -->
            <div class="search-box">
                <input type="text" class="ipt" placeholder="请输入要搜索的内容" /><button class="btnSearch">
            搜索
          </button>
            </div>
            <div id="suggest-list"></div>
        </div>
    </div>
    <script>
        $(function() {
            var flag = false;
            var cacheObj = {};
            // var timeId;
            $('.ipt').on('keyup', function() {
                // if (flag) {
                //     return;
                // }
                // flar = true;
                var kw = $(this).val().trim();
                if (kw.length <= 0) {
                    $('#suggest-list').html('').hide();
                    return;
                }
                if (cacheObj[kw]) {
                    var listTag = template('list-tpl', cacheObj[kw]);
                    $('#suggest-list').html(listTag).show();
                    return;
                }
                clearTimeout(timeId);
                timeId = setTimeout(function() {
                    $.ajax({
                        url: 'https://suggest.taobao.com/sug?q=' + kw,
                        dataType: 'jsonp',
                        success: function(data) {
                            if (data.result.length === 0) {
                                $('#suggest-list').empty().hide();
                            }
                            var listTag = template('list-tpl', data);
                            $('#suggest-list').html(listTag).show();
                            cacheObj[kw] = data;
                            flag = false;
                        }
                    })
                }, 2000);


            })
        })
    </script>
</body>

</html>